package com.yuchuang.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yuchuang.base.Enum;
import com.yuchuang.redis.RedisCache;
import com.yuchuang.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 *@authoe    :cy
 *@date      :14:02 2023-04-25
 *description:@Override :重写写实现类的方法
 *return     :
 **/
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisCache redisCache;
    private static LoginHandlerInterceptor loginHandlerInterceptor;
    public void writeMap(HttpServletResponse response,String enumStr) throws Exception {
        PrintWriter writer = null;
        writer = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        Enum enumData = Enum.valueOf(enumStr);
        map.put("code",enumData.getCode());
        map.put("message",enumData.getMessage());
        JSONObject json = new JSONObject(map);
        writer.print(json);
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        //设置返回的参数状态
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");

        String token = request.getHeader("token");
        if(token == null){
            writeMap(response,"ErrorTokenNull");
            return false;
        }else{
            //利用redis   实现单点登陆    更新token
            String redisToken = null;
            try{
                redisToken =  redisCache.getCacheObject("token_"+JWTUtil.getUserNickname(token));
            }catch (Exception e){

            }
            if(redisToken == null){
                //null值 没有登陆或者没有开启redis缓存
                writeMap(response,"ErrorRedisNull");
                return false;
            }else{
                //有值  header传来的token跟redisToken做对比   一样  验证时效性  成功允许登陆
                if(token.equals(redisToken)){
                    // 验证token的失效性   true 未失效  bu不拦截   false  拦截
                    Boolean isToken = JWTUtil.verify(token);
                    if(isToken){
                        //验证通过
                        return true;
                    }else{
                        writeMap(response,"ErrorToken");
                        return false;
                    }
                }else{
                    writeMap(response,"ErrorToken");
                    return false;
                }

            }
        }
    }
}
